package com.seventh.parkingrent.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seventh.parkingrent.Util.EncryptUtils;
import com.seventh.parkingrent.controller.form.ManagerForm;
import com.seventh.parkingrent.domain.Manager;
import com.seventh.parkingrent.dao.ManagerMapper;
import com.seventh.parkingrent.service.IManagerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.lang.annotation.Target;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2021-08-25
 */
@Service
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements IManagerService {
    @Resource
    private ManagerMapper managerMapper;

    @Override
    public Manager login(ManagerForm form) throws NoSuchAlgorithmException {
        @NotBlank String managerName = form.getManagerName();
        @NotBlank String originManagerPassword = form.getManagerPassword();
        //密码加密
        String password = EncryptUtils.encrypt(originManagerPassword);
        //编写查询条件
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_name",managerName);
        wrapper.eq("manager_password",password);

        Manager manager = managerMapper.selectOne(wrapper);
        return manager;
    }

    @Override
    public void update(Manager manager) {
        managerMapper.updateById(manager);
    }

    @Override
    public Boolean register(ManagerForm form) throws NoSuchAlgorithmException {
        //判断是否存在该账户名，若存在，返回false
        @NotBlank String managerName = form.getManagerName();
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_name",managerName);
        Manager one = managerMapper.selectOne(wrapper);
        if (null!=one) {
            return false;
        }
        //密码加密，将账户添加到manager表中
        Manager manager = new Manager();
        @NotBlank String originManagerPassword = form.getManagerPassword();
        String password = EncryptUtils.encrypt(originManagerPassword);
        form.setManagerPassword(password);
        BeanUtils.copyProperties(form, manager);
        int insert = managerMapper.insert(manager);

        return true;
    }

    @Override
    public List<String> getManagerName() {
        List<String> managerNames = managerMapper.selectManagerNames();
        return managerNames;
    }
}
